// pages/layerListPage/layerListPage.js
/*
  进入图层页面
  从全局数据中拿出图层数据渲染即可
*/
import {
  request
} from '../../request/index.js';
import {
  rightJudge
} from '../../lib/right.js';
var app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    // 图层数据
    layerList: [],
    // 控制详情页开关
    showModalStatus: false,
    // 详情页动画
    animationData: '',
    // 此时选中的图层
    selectedLayerName: '',
    // 
    selectedLayerId: '',
    // 图层所在的地图
    nowMap: '',
    // 地图名称
    nowMapName: '',
    // 新图层名称
    newLayerName: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // 取全局数据
    this.setData({
      layerList: app.globalData.layerGlobal
    })
    // 格式化时间
    if (this.data.layerList) {
      this.data.layerList.map((value, index) => {
        value.createdAt = new Date(value.createdAt).toLocaleDateString()
      })
      this.setData({
        layerList: this.data.layerList
      })
      // 从全局数据中获取激活的地图数据
      app.globalData.mapGlobal.map((v, i) => {
        if (v._id == app.globalData.activeMapIdGlobal) {
          this.setData({
            nowMap: v,
            nowMapName: v.mapName
          })
        }
      })
    } else {
      console.log('当前无图层！')
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.hideModal()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: async function () {
    // 重新设置全局数据
    app.globalData.layerGlobal = this.data.layerList;
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: async function () {
    // 重新设置全局数据
    app.globalData.layerGlobal = this.data.layerList;
    // 修改用户配置
    let userLayerSetting = []
    if (app.globalData.layerGlobal) {
      app.globalData.layerGlobal.map(v => {
        let tmp = {}
        tmp['userId'] = app.globalData.userIdGlobal
        tmp['layerId'] = v._id
        tmp['isVisible'] = v.isVisible
        userLayerSetting.push(tmp)
      })
      let res = await request({
        url: '/setting/updateSettingMany',
        method: 'PUT',
        data: userLayerSetting
      })
    } else {
      console.log('退出了layerListPage, 当前无数据需要更新')
    }
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  // 点击三个点
  handleLayerListTap: function (e) {
    // 设置选中图层
    this.setData({
      selectedLayerName: e.currentTarget.dataset.layername,
      selectedLayerId: e.currentTarget.dataset.layerid
    })
    // 显示遮罩层
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation
    animation.translateY(300).step()
    this.setData({
      animationData: animation.export(),
      showModalStatus: true
    })
    setTimeout(function () {
      animation.translateY(0).step()
      this.setData({
        animationData: animation.export()
      })
    }.bind(this), 200)
  },
  //隐藏对话框
  hideModal: function () {
    // 隐藏遮罩层
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation
    animation.translateY(300).step()
    this.setData({
      animationData: animation.export(),
    })
    setTimeout(function () {
      animation.translateY(0).step()
      this.setData({
        animationData: animation.export(),
        showModalStatus: false
      })
    }.bind(this), 200)
  },
  // 控制图层显示隐藏
  handleLayerVisible: function (e) {
    this.data.layerList.map((value, index) => {
      if (value.layerName == e.currentTarget.dataset.layername) {
        value.isVisible = !value.isVisible
      }
    })
    this.setData({
      layerList: this.data.layerList
    })
  },
  // 编辑图层
  editLayer: function (e) {
    // 判断权限
    if (app.globalData.teamUserRight != 2) {
      wx.showModal({
        title: '提示',
        content: '您还没有编辑权限！请联系管理员'
      })
    } else {
      this.setData({
        showModal: true
      })
      this.hideModal()
    }
  },
  close_mask: function () {
    this.setData({
      showModal: false
    })
  },
  // 输入字段
  inputModify: function (e) {
    this.setData({
      modifyLayerName: e.detail.value
    })
  },
  // 编辑图层点确定
  modifyLayerName: async function () {
    wx.showLoading({
      title: '加载中',
      mask: true
    });
    let sendData = {}
    sendData['layerName'] = this.data.modifyLayerName
    // 发送请求改数据库数据
    await request({
      url: '/layer/modify?layerId=' + this.data.selectedLayerId,
      method: 'PUT',
      data: sendData
    }, false)
    // 重新获取激活的地图的数据（图层-点）
    await this.updateLayerList(app.globalData.activeMapIdGlobal)
    this.setData({
      showModal: false
    })
    // 弹窗提示
    wx.hideLoading()
    wx.showToast({
      title: '修改成功！',
      icon: 'success'
    })
  },
  // 添加图层
  addLayer: function () {
    // 首先判断是否登录
    if (app.globalData.userInfo == null) {
      wx.showModal({
        title: '提示',
        content: '您还未登录，是否跳转登录？',
        success: res => {
          if (res.confirm) {
            wx.switchTab({
              url: '/pages/myPage/myPage',
            })
          }
        }
      })
    } else {
      // 判断权限
      if (app.globalData.teamUserRight != 2) {
        wx.showModal({
          title: '提示',
          content: '您还没有编辑权限！请联系管理员'
        })
      } else {
        this.setData({
          showModal2: true
        })
      }
    }
  },
  close_mask2: function () {
    this.setData({
      showModal2: false
    })
  },
  // 添加图层输入
  inputNewMap: function (e) {
    this.setData({
      newLayerName: e.detail.value
    })
  },
  // 添加图层确定
  handleAddLayerConfirm: async function () {
    wx.showLoading({
      title: '加载中',
      mask: true
    });
    let sendNewLayerData = {}
    sendNewLayerData['layerName'] = this.data.newLayerName
    sendNewLayerData['map_id'] = this.data.nowMap._id
    sendNewLayerData['isDefaultLayer'] = false
    sendNewLayerData['isVisible'] = false
    sendNewLayerData['markerCount'] = 0
    sendNewLayerData['fieldList'] = []
    this.setData({
      showModal2: false
    })
    // 调用添加图层接口
    let res = await request({
      url: '/layer',
      method: 'POST',
      data: sendNewLayerData
    }, false)
    // 新建用户配置
    let newSetting = {}
    newSetting['userId'] = app.globalData.userIdGlobal
    newSetting['layerId'] = res.data.data._id
    newSetting['isVisible'] = true
    await request({
      url: '/setting',
      method: 'POST',
      data: newSetting
    }, false)
    // 重新获取激活的地图的数据（图层-点）
    await this.updateLayerList(app.globalData.activeMapIdGlobal)
    // 弹窗
    wx.hideLoading()
    wx.showToast({
      title: '添加成功！',
      icon: 'success'
    })
  },
  // 删除图层
  deleteLayer: async function (e) {
    // 判断权限
    if (app.globalData.teamUserRight != 2) {
      wx.showModal({
        title: '提示',
        content: '您还没有编辑权限！请联系管理员'
      })
    } else {
      let userChoice = await wx.showModal({
        title: '提示',
        content: '确认要删除该图层?请谨慎操作'
      })
      if (userChoice.confirm) {
        wx.showLoading({
          title: '加载中',
          mask: true
        });
        await request({
          url: '/layer/' + this.data.selectedLayerId,
          method: 'DELETE'
        }, false)
        // 删除点
        await request({
          url: '/marker/multi/' + this.data.selectedLayerId,
          method: 'DELETE'
        }, false)
        // 删除配置
        await request({
          url: '/setting/deleteManyByLayerId/' + this.data.selectedLayerId,
          method: 'DELETE'
        }, false)
        this.hideModal()
        // 重新获取数据
        await this.updateLayerList(app.globalData.activeMapIdGlobal)
        wx.hideLoading();
      } else {

      }
    }
  },
  // 字段管理
  handleField: function (e) {
    wx.navigateTo({
      url: '../layerFieldPage/layerFieldPage?layerName=' + this.data.selectedLayerName + '&layerId=' + this.data.selectedLayerId,
    })
  },

  // 更新数据公共方法抽取
  async updateLayerList(mapId) {
    // 重新获取激活的地图的数据（图层-点）
    let res = await request({
      url: '/marker/testZty/' + mapId
    }, false)
    // 格式化时间
    res.data.data.map((value, index) => {
      value.createdAt = new Date(value.createdAt).toLocaleDateString()
    })
    // 获取点数据
    let userSetting = await request({
      url: '/setting/getSettingById/' + app.globalData.userIdGlobal
    }, false)
    res.data.data.forEach(v => {
      for (let setting of userSetting.data.data) {
        if (setting.layerId == v._id) {
          v.isVisible = setting.isVisible
        }
      }
    })
    this.setData({
      layerList: res.data.data
    })
  }
})